package 并发编程;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class Memoizerl<A, V> implements Computable<A, V> {
    private final Map<A, Future<V>> cache = new ConcurrentHashMap<A, Future<V>>();
    private final Computable<A, V> c;

    public Memoizerl(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public V compute(A arg) throws InterruptedException, ExecutionException {
        // while (true) {
        Future<V> f = cache.get(arg);
        if (f == null) {
            Callable<V> eval = new Callable<V>() {
                @Override
                public V call() throws Exception {
                    return c.compute(arg);
                }
            };
            FutureTask<V> ft = new FutureTask<V>(eval);
            f = cache.putIfAbsent(arg, ft);
            if (f == null) {
                f = ft;
                ft.run();
            }
            try {
                return f.get();
            } catch (CancellationException e) {
                cache.remove(arg, f);
            }
        }
        return f.get();
        //}
    }


    public static void main(String[] args) {
        //申明计算骨架
        Memoizerl<String, String> jg = new Memoizerl<>(new Computable<String, String>() {
            @Override
            public String compute(String arg) throws Exception {
                Thread.sleep(5000);
                System.out.println("准备返回结果");
                return arg + "_" + "2";
            }
        });
        try {
            //执行一次
            String res = jg.compute("1");
            //执行第二次
            String res2 = jg.compute("1");
            System.out.println(res);
            System.out.println(res2);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}